package com.happok.onlineclass.usermanagement.setting.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.happok.onlineclass.usermanagement.setting.dto.EmailSettingDTO;
import com.happok.onlineclass.usermanagement.setting.dto.EmailSettingInfoDTO;
import com.happok.onlineclass.usermanagement.setting.po.EmailPO;
import com.happok.onlineclass.usermanagement.setting.service.EmailDaoService;
import com.happok.onlineclass.usermanagement.setting.service.EmailService;
import com.happok.onlineclass.usermanagement.setting.utils.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

/**
 * 接口分类                        yapi 分类文件夹
 * 功能说明
 *
 * @author : chenac
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/10/12 11:22
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private EmailDaoService emailDaoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmailSetting(EmailSettingDTO emailSetting) {
        emailDaoService.updateEmailSetting(emailSetting);
        EmailPO email = emailDaoService.getEmail();
        String mailPwd = "";
        if (!ObjectUtils.isEmpty(email.getPassword())) {
            mailPwd = email.getPassword();
        } else {
            mailPwd = email.getAuthorizationCode();
        }
        EmailUtil.connectToEmail(email.getServer(), email.getAccount(), mailPwd);
    }

    @Override
    public EmailSettingInfoDTO getEmailSetting(boolean encrypt) {
        EmailPO email = emailDaoService.getEmail();
        EmailSettingInfoDTO emailSettingInfo = new EmailSettingInfoDTO();
        BeanUtil.copyProperties(email, emailSettingInfo);
        if (encrypt) {
            if (!ObjectUtils.isEmpty(emailSettingInfo.getPassword())) {
                emailSettingInfo.setPassword("******");
            }
            if (!ObjectUtils.isEmpty(emailSettingInfo.getAuthorizationCode())) {
                emailSettingInfo.setAuthorizationCode("******");
            }
        }
        return emailSettingInfo;
    }

    @Override
    public void checkAndConnectEmail() {
        EmailPO email = emailDaoService.getEmail();
        if (!ObjectUtils.isEmpty(email.getPassword())) {
            EmailUtil.connectToEmail(email.getServer(), email.getAccount(), email.getPassword());
        } else {
            EmailUtil.connectToEmail(email.getServer(), email.getAccount(), email.getAuthorizationCode());
        }
    }
}